<template>
  <div style="width: 100%">
    <div v-for="(item, index) in formData[data.field]" :key="index" class="more-input">
      <el-input
        v-model="item.value"
        :disabled="data.disabled"
        clearable
        :placeholder="data.placeholder ? data.placeholder : '请输入'"
        :maxlength="data.maxLength ? data.maxLength : Infinity"
        :show-word-limit="Boolean(data.maxLength)"
        @change="validMobile($event, data.field, index)"
      />
      <el-input v-model.trim="item.memo" :disabled="data.disabled" clearable placeholder="请输入备注" class="memo" />
      <div v-show="!data.disabled">
        <span
          v-if="form[data.field] && form[data.field].length && index === 0"
          class="MC_iconfont MC_icon-tianjia-yuan-xian"
          @click="add"
        ></span>
        <span v-else class="MC_iconfont MC_icon-shanchu2-xian" @click="remove(index)"></span>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { isNumber } from '@/common/utils/validate'

export default defineComponent({
  name: 'MoreInput',
  props: {
    form: {
      type: Object,
      default: () => ({})
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:form'],
  setup(props, { emit }) {
    const formData: any = computed({
      get: () => props.form,
      set: (val) => emit('update:form', val)
    })

    const remove = (index: number) => {
      formData.value[props.data.field].splice(index, 1)
    }

    const add = () => {
      if (formData.value[props.data.field] && formData.value[props.data.field].length > 9) {
        return ElMessage.error('最多允许添加10个')
      }
      formData.value[props.data.field].push({})
    }

    const validMobile = (val: string, field: string, idx: number) => {
      if (field !== 'mobile') {
        return
      }
      if (!isNumber(val)) {
        console.log(!isNumber(val), formData.value)
        formData.value[field][idx].value = '' // 清空数据
        ElMessage.error('手机号只能输入数字')
      }
    }

    return { formData, add, remove, validMobile }
  }
})
</script>

<style lang="stylus" scoped>
.more-input
  display flex
  align-items center
  margin-top 6px
  &:first-child
    margin-top: 0
  .memo
    margin-left 12px
  span
    cursor pointer
    margin-left 6px
    &.MC_icon-tianjia-yuan-xian
      color: var(--mc-main-color)
    &.MC_icon-shanchu2-xian
      color: rgba(0, 0, 0, 0.38)
</style>
